package com.peng.service.impl;

import com.alibaba.fastjson.JSON;
import com.peng.dao.pojo.SysUser;
import com.peng.service.LoginService;
import com.peng.service.SysUserService;
import com.peng.utils.JWTUtils;
import com.peng.vo.ErrorCode;
import com.peng.vo.Result;
import com.peng.vo.params.LoginParam;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public Result login(LoginParam loginParam) {
        String account = loginParam.getAccount();
        String password = loginParam.getPassword();
        if (account == null || password == null) {
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }
        String md5 = String.valueOf(DigestUtils.md5Hex(password + "chihiro"));
        SysUser user = sysUserService.findUser(account, md5);
        if (user == null) {
            return Result.fail(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(), ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
        }
        String token = JWTUtils.createToken(user.getId());
        redisTemplate.opsForValue().set("TOKEN_"+token, JSON.toJSONString(user),1, TimeUnit.DAYS);
        return Result.success(token);
    }

    @Override
    public SysUser findUserByToken(String token) {
        if (token==null){
            return null;
        }
        Map<String, Object> map = JWTUtils.checkToken(token);
        if (map==null){
            return null;
        }
        String s = redisTemplate.opsForValue().get("TOKEN_" + token);
        if (s==null){
            return null;
        }
        SysUser parse = JSON.parseObject(s, SysUser.class);
        return parse;
    }

    @Override
    public Result loginOut(String token) {
        if (token==null){
            return Result.fail(ErrorCode.LOGINOUT_ERROR.getCode(), ErrorCode.LOGINOUT_ERROR.getMsg());
        }
        redisTemplate.delete("TOKEN_"+token);
        return Result.success(null);
    }

}
